<?php

/**
 * 试卷管理控制器
 */
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\CompanyExaminationPostRequest;
use App\Models\Company;
use Illuminate\Support\Facades\Response;
use App\Models\Questions;
use App\Models\Examination;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\CompanyJobs;

class ExaminationsController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if(!$this->user->can('viewExam')) abort(405);

        $examinations = Examination::paginate(20);
        return view('admin.enterprise.examination.index')
                ->with('examinations', $examinations);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(!$this->user->can('editExam')) abort(405);
        // 获取题库列表-
        $questions = Questions::all();
        $companys = Company::all();
        return view('admin.enterprise.examination.edit')->with('blademod', 'add')
                    ->with('companys', $companys)
                    ->with('questions', $questions);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(CompanyExaminationPostRequest $request)
    {
        if(!$this->user->can('viewExam')) 
            return $this->formatJson('error',$this->permerror);
        
        $examination_id = $request->get('id', 0);
        /*试题ID数组*/
        $question_ids = $request->get('question_id');
        $post = array_except($request->all(), ['_token', 'id', 'question_id']);
        $post['question_count'] = count($question_ids);
        $post['score'] = $post['score']?:1;
        DB::beginTransaction();
        try{
            if($examination_id > 0 AND !empty($post)) {
                $company_examina = Examination::find($examination_id);
                foreach ($post as $key => $val) {
                    $company_examina->$key = $val;
                }
                $company_examina->save();
            } else{
                $company_examina = Examination::firstOrCreate($post);
            }
            $company_examina->questions()->sync($question_ids);
            DB::commit();
        }catch (\PDOException $e){
            Log::info(['企业保存试卷失败'=>$e->getMessage()]);
            DB::rollback();
            return $this->formatJson('error','保存试卷失败！');
        }
        return Response::json(array('id'=>$company_examina->id,'status'=>'success','msg'=>'保存数据成功！','redirectUrl'=>'/admin/enterprise/examinations'));
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        if(!$this->user->can('viewExam')) abort(405);
        if(empty($id) || $id == 0)
            $question = Questions::orderBy('created_at','DESC')->get();
        else 
            $question = Questions::where('company_id','=',$id)->get();
        
        if(count($question)>0)
            return $this->formatJson('success','成功！',$question);
        
        return $this->formatJson('error','<a href="/admin/enterprise/questions"><font color="red">没有更多数,请先录入数据！</font></a>');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        if(!$this->user->can('viewExam')) abort(405);
        $selected = array();
        $companys = Company::all();
        $examination = Examination::find($id);
        if(empty($examination->company_id) || $examination->company_id==0 )
        {
            $questions = Questions::all();
        }
        else 
        {
            $questions = Questions::where('company_id','=',$examination->company_id)->get();
        }
        $selected = array_fetch($examination->questions->toArray(),'id');
        return view('admin.enterprise.examination.edit')->with('examination', $examination)
                    ->with('companys', $companys)
                    ->with('questions', $questions)
                    ->with('selected', $selected);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($examination_id)
    {
        if(!$this->user->can('deleteExam')) abort(405);
        
        $examination = Examination::find($examination_id);
        
        if(empty($examination))
            return $this->formatJson('error','资源不存在！');
        $hasjob = CompanyJobs::where('exam_id','=',$examination_id)->first();
        if(!empty($hasjob))
            return $this->formatJson('error','已有职位关联该考试，请先取消关联！');
        
        DB::beginTransaction();
        try{
            $examination->delete();
            $examination->questions()->detach();
            DB::commit();
            return $this->formatJson('success','试卷 ['. str_limit($examination->name, 15) . '] 删除成功!');
        }catch (\PDOException $e){
            DB::rollback();
            Log::info(['删除试卷失败'=>$e->getMessage()]);
            return $this->formatJson('error','删除试卷失败！');
        }
        
    }
    

}
